package com.tdam2011.grupo02.ui;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarActivity;
import com.tdam2011.grupo02.connectivity.ConnectivityInformationSingleton;
import com.tdam2011.grupo02.domain.DialogInfo;
import com.tdam2011.grupo02.domain.Usuario;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.content.DialogInterface.OnCancelListener;

public class LoginFragmentActivity extends ActionBarActivity {

	private Button login;
	private EditText user;
	private EditText password;
	private CheckBox recordarUsuarioPassword;
	private String notificacion;
	private Context context;

	private static final int REGISTRAR_USUARIO = 0;
	private static final String LOGIN_SETTINGS = "LoginPreferences";
	private static final String REMEMBER_USER_PASSWORD = "rememberUserPassword";
	private static final String USER = "user";
	private static final String PASSWORD = "password";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		context = this;

		setTitle(R.string.loginSesion);

		user = (EditText) findViewById(R.id.txt_login_user);
		password = (EditText) findViewById(R.id.txt_login_password);
		recordarUsuarioPassword = (CheckBox) findViewById(R.id.chkbxRecordarLogin);
		recordarUsuarioPassword.setChecked(recordarUsuarioContrasenia());
		recordarUsuarioPassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (recordarUsuarioPassword.isChecked()) {
					SharedPreferences preferences = getSharedPreferences(
							LOGIN_SETTINGS, MODE_PRIVATE);
					SharedPreferences.Editor edit = preferences.edit();
					edit.clear();
					edit.putBoolean(REMEMBER_USER_PASSWORD,
							recordarUsuarioPassword.isChecked());
					edit.putString(USER, user.getText().toString());
					edit.putString(PASSWORD, password.getText().toString());
					edit.commit();
				} else {
					SharedPreferences preferences = getSharedPreferences(
							LOGIN_SETTINGS, MODE_PRIVATE);
					SharedPreferences.Editor edit = preferences.edit();
					edit.clear();
					edit.putBoolean(REMEMBER_USER_PASSWORD,
							recordarUsuarioPassword.isChecked());
					edit.commit();
				}
			}
		});

		login = (Button) findViewById(R.id.btn_login);
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (user.getText().toString().trim().length() == 0
						|| password.getText().toString().trim().length() == 0)
					showDialog(DialogInfo.TYPE_ALERT_EMPTY_USER_PASSWORD);
				else {
					Usuario usuario = new Usuario();
					usuario.set_id(user.getText().toString());
					usuario.setPassword(password.getText().toString());

					boolean aux = DatabaseHelperSingleton.getInstance(context)
							.getDatabaseHelper().existsUser(usuario);

					if (aux) {
						initMain();
					} else {
						showDialog(DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD);
					}
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REGISTRAR_USUARIO) {
			if (data != null) {
				Bundle datos = data.getExtras();
				SharedPreferences preferences = getSharedPreferences(
						LOGIN_SETTINGS, MODE_PRIVATE);
				SharedPreferences.Editor edit = preferences.edit();
				edit.clear();
				edit.putBoolean(REMEMBER_USER_PASSWORD,
						recordarUsuarioPassword.isChecked());
				edit.putString(USER, datos.getString(USER));
				edit.putString(PASSWORD, datos.getString(PASSWORD));
				edit.commit();
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences preferences = getSharedPreferences(LOGIN_SETTINGS,
				MODE_PRIVATE);
		user.setText(preferences.getString(USER, ""));
		password.setText(preferences.getString(PASSWORD, ""));
	}

	private boolean recordarUsuarioContrasenia() {
		SharedPreferences preferences = getSharedPreferences(LOGIN_SETTINGS,
				MODE_PRIVATE);
		return preferences.getBoolean(REMEMBER_USER_PASSWORD, false);
	}

	// Dialogs

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;

		switch (id) {
		case DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD:
			dialog = createAlertDialog(DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD);
			break;

		case DialogInfo.TYPE_ALERT_EMPTY_USER_PASSWORD:
			dialog = createAlertDialog(DialogInfo.TYPE_ALERT_EMPTY_USER_PASSWORD);
			break;

		case DialogInfo.TYPE_ALERT:
			dialog = createAlertDialog(DialogInfo.TYPE_ALERT);
			break;

		case DialogInfo.TYPE_OK_CANCEL:
			dialog = createOkCancelDialog();
			break;
		}
		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}

	private Dialog createAlertDialog(int type) {
		DialogInfo dialogInfoToShow = new DialogInfo();

		switch (type) {
		case DialogInfo.TYPE_ALERT_WRONG_USER_PASSWORD:
			dialogInfoToShow.setBtLabelOk(getString(R.string.alertBtnOk));
			dialogInfoToShow
					.setTitle(getString(R.string.alertTitleInitSesionError));
			dialogInfoToShow
					.setMessage(getString(R.string.alertMessageUserPasswordWrong));
			break;

		case DialogInfo.TYPE_ALERT_EMPTY_USER_PASSWORD:
			dialogInfoToShow.setBtLabelOk(getString(R.string.alertBtnOk));
			dialogInfoToShow.setTitle(getString(R.string.alertTitleWarning));
			dialogInfoToShow
					.setMessage(getString(R.string.alertMessageEnterUserPassword));
			break;

		case DialogInfo.TYPE_ALERT:
			dialogInfoToShow.setBtLabelOk(getString(R.string.alertBtnOk));
			dialogInfoToShow.setTitle(getString(R.string.alertTitleWarning));
			dialogInfoToShow
					.setMessage(getString(R.string.msgNoInternetConnection));
			break;
		}

		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon_alert)
				.setTitle(dialogInfoToShow.getTitle())
				.setPositiveButton(dialogInfoToShow.getBtLabelOk(), null)
				.setMessage(dialogInfoToShow.getMessage()).create();

		return dialog;
	}

	private Dialog createOkCancelDialog() {
		DialogInfo info = new DialogInfo();
		info.setTitle(getString(R.string.alertTitleWelcome));
		info.setMessage(notificacion); // info.setMessage(getString(R.string.alertMessageNotifications));
		info.setBtLabelOk(getString(R.string.alertBtnOk));
		info.setBtLabelCancel(getString(R.string.alertBtnCancel));
		info.setType(DialogInfo.TYPE_OK_CANCEL);

		android.content.DialogInterface.OnClickListener optionOk = new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				initMain();
			}
		};

		android.content.DialogInterface.OnClickListener optionCancel = new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		};

		OnCancelListener optionCancelDefault = new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
			}
		};

		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon_android)
				.setOnCancelListener(optionCancelDefault)
				.setTitle(info.getTitle())
				.setPositiveButton(info.getBtLabelOk(), optionOk)
				.setNegativeButton(info.getBtLabelCancel(), optionCancel)
				.setMessage(info.getMessage()).create();

		return dialog;
	}

	public void initMain() {
		Intent intent = new Intent(LoginFragmentActivity.this,
				MainActivity.class);
		startActivity(intent);
	}

	// OPTIONS MENU

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.options_menu_login, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		case R.id.menu_new_user:
			boolean isConnection = ConnectivityInformationSingleton
					.getInstance(this).getConnectivityInformation()
					.isInternetConnectionAvailable();

			if (isConnection)
				intent = new Intent(this, RegistrarUsuarioActivity.class);
			else
				showDialog(DialogInfo.TYPE_ALERT);
			break;
		}

		if (intent != null)
			startActivity(intent);

		return super.onOptionsItemSelected(item);
	}
}
